package com.snack.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.snack.shop.dto.ProductStatsDTO;
import com.snack.shop.entity.Product;
import com.snack.shop.mapper.ProductMapper;
import com.snack.shop.service.StatsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 统计服务实现
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class StatsServiceImpl implements StatsService {

    private final ProductMapper productMapper;

    @Override
    public ProductStatsDTO getProductStats(Integer stockThreshold) {
        int threshold = (stockThreshold != null ? stockThreshold : 10);

        ProductStatsDTO dto = new ProductStatsDTO();

        // 总数
        Long total = productMapper.selectCount(new LambdaQueryWrapper<>());
        dto.setTotal(total);

        // 已上架
        Long onSale = productMapper.selectCount(new LambdaQueryWrapper<Product>()
                .eq(Product::getStatus, 1));
        dto.setOnSale(onSale);

        // 已下架
        Long offSale = productMapper.selectCount(new LambdaQueryWrapper<Product>()
                .eq(Product::getStatus, 0));
        dto.setOffSale(offSale);

        // 库存预警（与列表页一致：stock <= threshold）
        Long lowStock = productMapper.selectCount(new LambdaQueryWrapper<Product>()
                .le(Product::getStock, threshold));
        dto.setLowStock(lowStock);

        return dto;
    }
}
